<!--  园区信息修改   -->
<template>
    <div id="myMain">
        <div class="myMain-padding displayFlexC">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
                <el-form-item label="园区名称" prop="name">
                    <el-input v-model="ruleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="园区类型" prop="parkType">
                    <el-input v-model="ruleForm.parkType"></el-input>
                </el-form-item>
                <el-form-item label="园区地址" prop="address">
                    <el-input v-model="ruleForm.address"></el-input>
                </el-form-item>
                <el-form-item label="园区简介:" prop="introduce">
                    <el-input v-model="ruleForm.introduce" type="textarea" :autosize="{ minRows: 2, maxRows: 10}"></el-input>
                </el-form-item>
                <el-form-item label="园区面积" prop="area">
                    <el-input v-model="ruleForm.area"></el-input>
                </el-form-item>
                <el-form-item label="房屋数量" prop="houseNum">
                    <el-input v-model="ruleForm.houseNum"></el-input>
                </el-form-item>
                <el-form-item label="园区banner图:">
                    <el-upload
                        action="http://192.168.1.193:9307/api-user/open/uploadFile"
                        list-type="picture-card"
                        ref="myUpload1"
                        :headers="myHeaders"
                        :on-remove="handleRemove"
                        :before-upload="beforeAvatarUpload"
                        :on-success="handleAvatarSuccess"
                        :file-list="fileList">
                        <i class="el-icon-plus"></i>
                        <div slot="tip" class="el-upload__tip">上传的图片只能是 JPG 或者 PNG 格式!</div>
                    </el-upload>
                    <!-- <span v-for="(item, index) in ruleForm.bannerImage" :key="index">
                        <img width="200px" :src="item" alt="">
                    </span> -->
                </el-form-item>
                <el-form-item label="园区小图:" >
                    <el-upload
                    action="http://192.168.1.193:9307/api-user/open/uploadFile"
                    list-type="picture-card"
                    ref="myUpload2"
                    :limit="1"
                    :on-remove="handleRemove2"
                    :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccess2"
                    :file-list="fileList2">
                    <i class="el-icon-plus"></i>
                    <div slot="tip" class="el-upload__tip">上传的图片只能是 JPG 或者 PNG 格式! 且只能上传1张小图。</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="联系人" prop="contacts">
                    <el-input v-model="ruleForm.contacts"></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="ruleForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="联系邮箱" prop="email">
                    <el-input v-model="ruleForm.email"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import Cookies from 'js-cookie'
import { getParkInfoById } from '@/api/Data_filling'
import { putParkInfo } from '@/api/parkManage'
export default {
//import引入的组件需要注入到对象中才能使用
components: {},
data() {
    var checkEmail = (rule, value, callback) => {
        const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
        if (!value) {
            return callback(new Error('邮箱不能为空'))
        }
        setTimeout(() => {
            if (mailReg.test(value)) {
                callback()
            } else {
                callback(new Error('请输入正确的邮箱格式'))
            }
        }, 100)
    }
    var checkPhone = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('请输入联系电话'))
        } else if (!(/^1[34578]\d{9}$/.test(value))) {
            callback(new Error('请输入正确的手机号码'))
        } else {
            callback()
        }
    }
    var checkNumber = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('请输入数值'))
        } else if (!(/[0-9]/.test(value))) {
            callback(new Error('只能填写数字'))
        } else {
            callback()
        }
    }
    //这里存放数据
    return {
        parkId: Cookies.get('parkId'),
        fileList: [],
        fileList2: [],
        ruleForm: {
            name: null,
            parkType: null,
            address: null,
            introduce: null,
            area: null,
            houseNum: null,
            contacts: null,
            phone: null,
            email: null,
            bannerImage: [],
            minImageUrl: []
        },
        rules: {
            name: [
                { required: true, trigger: 'blur', message: '请输入园区名称' },
            ],
            parkType: [
                { required: true, trigger: 'blur', message: '请选择园区类型' }
            ],
            address: [
                { required: true, trigger: 'blur', message: '请输入园区地址' }
            ],
            introduce: [
                { required: true, trigger: 'blur', message: '请输入园区简介' }
            ],
            area: [
                { required: true, validator: checkNumber, trigger: 'blur'  }
            ],
            houseNum: [
                { required: true, validator: checkNumber, trigger: 'blur'  }
            ],
            contacts: [
                { required: true, trigger: 'blur', message: '请输入联系人' }
            ],
            phone: [
                { required: true, validator: checkPhone, trigger: 'blur'  }
            ],
            email: [
                {  required: true, validator: checkEmail, trigger: 'blur' }
            ]
        },
        myHeaders:{},
    };
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
    init(){
        getParkInfoById(this.parkId).then(res => {
            let result = JSON.parse(JSON.stringify(res.data))
            let banner = result.bannerImage.split(',')
            banner.forEach(ele => {
                this.fileList.push( {url: ele} )
            });
            let min = result.minImage.split(',')
            min.forEach(ele => {
                this.fileList2.push( {url: ele} )
            });
            this.ruleForm = result
        })
    },
    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
                this.$confirm('此操作修改园区信息, 是否继续?', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let arr = []
                    this.fileList.forEach(ele => {
                        arr.push(ele.url)
                    })
                    this.ruleForm.bannerImage = arr.join(",")
                    let arr2 = []
                    this.fileList2.forEach(ele => {
                        arr2.push(ele.url)
                    })
                    this.ruleForm.minImage = arr2.join(",")
                    console.log("this.ruleForm", this.ruleForm)
                    putParkInfo(this.ruleForm).then(res => {
                        console.log("success res ", res)
                        this.$message({type: 'success',message: '修改成功!'});
                    })
                })
          } else {
            this.$message({type: 'error',message: '校验失败!'});
            return false;
          }
        });
    },
    // 上传
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList = fileList
    },
    handleRemove2(file, fileList) {
      console.log(file, fileList);
      this.fileList2 = fileList
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJPG) {
        this.$message.error('上传的图片只能是 JPG 或者 PNG 格式!');
      }
      return isJPG;
    },
    handleAvatarSuccess(res, file) {
      console.log("res", res)
      res.data.forEach(ele => {
            this.fileList.push({url: ele})
      });
    },
    handleAvatarSuccess2(res, file) {
      console.log("res", res)
      res.data.forEach(ele => {
            this.fileList2.push({url: ele})
      });
    },
},
//生命周期 - 创建完成（可以访问当前this实例）
created() {

},
//生命周期 - 挂载完成（可以访问DOM元素）
mounted() {
    this.init()
},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
@import '../../styles/all';
</style>